<!--  -->
<template>
  <div class="users">
    <el-card>
      <!-- 搜索区域开始 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input placeholder="根据用户名搜索" v-model="queryInfo.username"> </el-input>
        </el-col>
        <el-col :span="3">
          <el-button @click="clear">清除</el-button>
          <el-button type="primary" @click="getUserLists">搜索</el-button>
        </el-col>
        <el-col :span="5"> </el-col>
        <el-col class="right" :span="4">
          <el-button type="success" icon="el-icon-edit" @click="dialogVisible = true">新增用户</el-button>
        </el-col>
      </el-row>
      <!-- 搜索区域结束 -->

      <!-- 提示框区域开始 -->
      <el-alert type="info" show-icon :closable="false">
        <span slot="title">共条{{ getlist.length }}记录</span>
      </el-alert>
      <!-- 提示框区域结束 -->

      <!-- 表格区域开始 -->
      <el-table :data="getlist" boeder stripe>
        <el-table-column label="序号" type="index" width="100px"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="phone" label="联系电话"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="permission_group_title" label="权限组名称"> </el-table-column>
        <el-table-column prop="role" label="角色"> </el-table-column>
        <el-table-column prop="date" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle plain @click="upDate(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle plain @click="dele(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格区域结束 -->
      <!-- 分页功能开始 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 分页功能结束 -->
    </el-card>

    <!-- 新增用户对话框开始 -->
    <el-dialog :visible.sync="dialogVisible" width="50%" @close="listDialogClosed">
      <div slot="title" class="establishUser">创建用户</div>
      <el-form :model="addUserForm" label-width="100px" ref="listFromRef" :rules="usrRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="addUserForm.role"></el-input>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select v-model="addUserForm.permission_group_id" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="addUserForm.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="介绍">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="textarea"> </el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增用户对话框结束 -->

    <!-- 修改用户对话框开始 -->
    <el-dialog :visible.sync="isUpdateShow" width="50%">
      <div slot="title" class="establishUser">编辑用户</div>
      <el-form :model="upDateUserItem" label-width="100px" :rules="userRules" ref="userFrom">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="upDateUserItem.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="username">
          <el-input v-model="upDateUserItem.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="username">
          <el-input v-model="upDateUserItem.role"></el-input>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select v-model="value" placeholder="请选择">
            <el-option :value="upDateUserItem.permission_group_title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="upDateUserItem.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="介绍">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="textarea"> </el-input>
        </el-form-item> -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isUpdateShow = false">取 消</el-button>
        <el-button type="primary" @click="upDateUsersuccess">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框结束 -->
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getUserList, upDateUser, addUser, deleteUser } from '../../api/user/user'

export default {
  name: 'Users',
  components: {},

  props: {},
  data() {
    // 这里存放数据
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    return {
      addUserForm: {
        sex: '1',
        username: '',
        password: '123456',
        phone: '',
        permission_group_id: 1,
        email: '',
        role: ''
      },

      // kkk: { avatar: '', email: '1909415275@qq.om', introduction: '6666', password: '123456', permission_group_id: 9, phone: '135830711', role: '1', username: '22222', disabled: true },
      // input: '',
      // 用户列表数据
      getlist: [],
      dialogVisible: false,
      isUpdateShow: false,
      // 修改用户
      ruleForm: {},
      // 添加用户
      // addForm: {
      //   email: '',
      //   permission_group_id: '1',
      //   role: '',
      //   phone: '',
      //   // mobile: '',
      //   username: '',
      // },
      // 表单规则
      usrRules: {
        username: [
          {
            required: true,
            message: '请输入登录名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 5,
            message: '长度在3到5个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }
        ]
      },
      userRules: {
        username: [{ required: true, message: '请输入用户名称', trigger: 'blur' }]
        // phone: [{required: true, message: '请输入手机号', trigger: 'blur'}]
      },

      // 选择器
      value: '',
      options: [
        {
          value: 1,
          label: 1
        },
        {
          value: 2,
          label: 2
        }
      ],

      queryInfo: {
        keyword: '',
        //   页码
        page: 1,
        //   每页显示条数
        pagesize: 5,
        username: ''
      },
      total: 0,
      upDateUserItem: {}
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getUserLists()
    // 监听表单关闭事件
    // this.getUserSimple();
  },
  // 方法集合
  methods: {
    //  获取用户列表
    async getUserLists() {
      try {
        const { data } = await getUserList(this.queryInfo)
        // this.getlist = data
        this.getlist = data.list
        // console.log(getlist, 'getlist');
        this.total = data.counts
        // console.log(this.getlist);
      } catch (err) {
        console.log('获取失败')
      }
    },
    // 分页功能
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserLists()
    },
    handleCurrentChange(newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getUserLists()
    },

    // 修改用户
    upDate(current) {
      this.upDateUserItem = current
      this.isUpdateShow = true
    },
    // 删除
    async dele(id) {
      // console.log(id);
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消')
      const { data } = await deleteUser(id)
      console.log(data)
      console.log('删除成功')
      this.$message.success('删除成功')
      this.getUserLists()
    },
    // 监听表单关闭事件
    listDialogClosed() {
      this.$refs.userFrom.resetFields()
    },
    // 修改成功关闭对话框
    upDateUsersuccess() {
      try {
        // console.log(this.upDateUserItem);

        this.$refs.userFrom.validate(async valid => {
          if (!valid) {
            return this.$message.error('请填写完整信息')
          } else {
            await upDateUser(this.upDateUserItem.id, {
              username: this.upDateUserItem.username,
              email: this.upDateUserItem.email,
              permission_group_id: this.upDateUserItem.permission_group_id
            })
            this.getUserLists()
            // this.upDateUserItem = [];
            this.email = this.upDateUserItem.email
            // (this.upDateUserItem.role = '', (this.upDateUserItem.phone = '';
            this.isUpdateShow = false

            // console.log('修改成功');
            this.$message.success('修改成功')
          }
        })
      } catch (err) {
        console.log('修改失败')
      }
      this.isUpdateShow = false
    },
    // listDialogClosed() {
    //   this.$refs.listFromRef.resetFields()
    // },
    // 添加
    addUsers() {
      try {
        this.$refs.listFromRef.validate(async valid => {
          if (!valid) {
            return this.$message.error('请填写完整信息')
          } else {
            const { data } = await addUser({
              email: this.addUserForm.email,
              password: '123456',
              permission_group_id: 2,
              sex: '1',
              phone: this.addUserForm.phone,
              username: this.addUserForm.username
              // role: this.addUserForm.role
            })
            // console.log("添加成功");
            this.$message.success('添加成功')
            this.getlist.unshift(data)
            this.getUserLists()
            this.dialogVisible = false
          }
        })
      } catch (err) {
        console.log('添加失败')
      }
    },
    getLists() {
      this.getUserLists(this.queryInfo)
    },
    // 搜索
    clear() {
      this.queryInfo.username = ''
      this.getUserLists()
    }
  },

  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
}
</script>
<style lang="less" scoped>
.users {
  // .el-card {
  //   margin-right: 20px;
  // }
  // padding-right: 20px;

  // min-width: 100%;
  // min-width: 1200px;
  .is-plain {
    display: inline-block;
  }
  height: 100%;
  // padding: 10px;
  .el-row {
    width: 100%;
    .el-col-3 {
      width: 50%;
    }
    .right {
      float: right;
      padding: 0;
      margin: 0;
    }
  }
  .el-alert {
    margin-top: 20px;
    margin-bottom: 30px;
  }
  .el-dialog {
    padding: 0;
    margin: 0;
  }
  .establishUser {
    height: 50px;
    padding: 0;
    margin: 0;
    // background-color: pink;
    font-size: 28px;
  }
  .el-form {
    transform: translateX(20%);
    // padding: 30, 20;
    .el-form-item {
      text-align: center;
      width: 400px;
      align-content: center;
      .el-select {
        float: left;
      }
    }
  }
}
.el-dialog__header {
  padding: 0px;
  background-color: pink;
}
.el-pagination {
  margin: 20px 10px;
  float: right;
}
header {
  margin-right: 20px;
  height: 34px;
  background-color: #fff;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 30px;
}
</style>
